package com.yzh.wanandroid.component.fragment


import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.navigation.NavDirections
import androidx.navigation.Navigation
import com.yzh.wanandroid.R
import com.yzh.wanandroid.StartNavigationDirections
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.component.activity.MainActivity
import com.yzh.wanandroid.component.app.MainApplication
import com.yzh.wanandroid.databinding.FragmentMainBinding
import com.yzh.wanandroid.databinding.NavHeaderMainBinding
import com.yzh.wanandroid.expand.view.initDrawerLayout
import com.yzh.wanandroid.expand.view.initNavigationView
import com.yzh.wanandroid.expand.view.initViewPager2
import com.yzh.wanandroid.utils.*
import com.yzh.wanandroid.view.LoadingDialog
import com.yzh.wanandroid.vm.MainFragmentVm


/**
 *  主页fragment
 */
class MainFragment : MvvmFragment<FragmentMainBinding, MainFragmentVm>() {

    private val TAG = "MainFragment"

    private lateinit var mNavHeaderMainBinding: NavHeaderMainBinding

    override fun getLayoutId() = R.layout.fragment_main

    override fun initViewModel(): MainFragmentVm = createViewModel()

    lateinit var mNightModeItem: MenuItem

    private val mLoadingStateDialog: LoadingDialog by lazy { LoadingDialog(requireContext()) }

    override fun initView(view: View) {
        initDrawerLayout()
        initViewPager()
        initNavHeaderView()
        initNavigationView()
        onLoginStateChanged()
        logoutState()
    }

    override fun initData() {}

    /**
     * 初始化并viewPager
     */
    private fun initViewPager() {
        mBinding.run {
            mainViewpager.initViewPager2(activity as MainActivity)
            bottomNavigation.initNavigationView {
                when (it) {
                    R.id.fragment_home -> mainViewpager.setCurrentItem(PAGER_HOME, false)
                    R.id.fragment_square -> mainViewpager.setCurrentItem(PAGER_SQUARE, false)
                    R.id.fragment_public -> mainViewpager.setCurrentItem(PAGER_PUBLIC, false)
                    R.id.fragment_project -> mainViewpager.setCurrentItem(PAGER_PROJECT, false)
                }
            }
        }
    }

    /**
     * 初始化DrawerLayout
     */
    private fun initDrawerLayout() {
        mBinding.run {
            mainTitleLayout.titleText.setText(R.string.main_pager)
            mainDrawerLayout.initDrawerLayout(requireActivity(), mainTitleLayout.toolbar)
        }
    }

    /**
     * 初始化侧边栏头部
     */
    private fun initNavHeaderView() {
        mNavHeaderMainBinding = DataBindingUtil.inflate(
            layoutInflater,
            R.layout.nav_header_main,
            mBinding.mainNavigation,
            true
        )
        mNavHeaderMainBinding.run {
            mainFragment = this@MainFragment
            mainFragmentVm = mViewModel
        }
    }

    /**
     * 初始侧边栏列表
     */
    private fun initNavigationView() {
        mBinding.run {
            mainNavigation.menu.findItem(R.id.nav_logout).isVisible = mViewModel.isLogin()
            mNightModeItem = mainNavigation.menu.findItem(R.id.nav_night_mode)
            changeNightModeText(mNightModeItem, mViewModel.isNightMode())
            mainNavigation.setNavigationItemSelectedListener {
                when (it.itemId) {
                    R.id.nav_score -> {
                        onMenuItemClick(mainNavigation, MainFragmentDirections.toUserInfo())
                    }
                    R.id.nav_collect -> {
                        onMenuItemClick(mainNavigation, MainFragmentDirections.toCollectFragment())
                    }
                    R.id.nav_share -> {
                        Toast.makeText(activity, R.string.my_share, Toast.LENGTH_SHORT).show()
                    }
                    R.id.nav_todo -> {
                        Toast.makeText(activity, R.string.nav_todo, Toast.LENGTH_SHORT).show()
                    }
                    R.id.nav_night_mode -> {
                        MainApplication.appInstance.changeNightMode(mViewModel.chageNightMode())
                    }
                    R.id.nav_setting -> {
                        Navigation.findNavController(mainNavigation)
                            .navigate(MainFragmentDirections.toSetting())
                    }
                    R.id.nav_logout -> {
                        showLoginOutDialog()
                    }
                }
                false
            }
        }
    }

    private fun changeNightModeText(item: MenuItem, isNightMode: Boolean) {
        if (isNightMode) {
            item.setTitle(R.string.nav_day_model)
        } else {
            item.setTitle(R.string.nav_night_mode)
        }
    }

    /**
     *  登录状态改变更新侧边栏头部信息
     */
    private fun onLoginStateChanged() {
        mViewModel.userLogin.observe(this) {
            mNavHeaderMainBinding.run {
                tvUsername.text = it.username
                tvUserRank.text = it.rank
                tvUserGrade.text = it.level
                mBinding.mainNavigation.menu.findItem(R.id.nav_logout).isVisible =
                    mViewModel.isLogin()
            }
            if (mLoadingStateDialog.isShowing) {
                mLoadingStateDialog.cancel()
            }
            // 获取用户名失败
            if (it.errorCode != 0) {
                Toast.makeText(requireContext(), it.errorMessage, Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 退出时显示loading
     */
    private fun logoutState() {
        mViewModel.logOutState.observe(this) {
            when (it) {
                LOGOUT_LOADING -> mLoadingStateDialog.show()
                LOGOUT_ERROR -> mLoadingStateDialog.cancel()
                LOGOUT_SUCCESS -> {
                    mNavHeaderMainBinding.run {
                        tvUsername.text = getString(R.string.go_login)
                        tvUserRank.text = getString(R.string.default_value)
                        tvUserGrade.text = getString(R.string.default_value)
                        mBinding.mainNavigation.menu.findItem(R.id.nav_logout).isVisible =
                            mViewModel.isLogin()
                    }
                    mLoadingStateDialog.cancel()
                }
            }
        }
    }

    /**
     *  显示退出时的dialog
     */
    private fun showLoginOutDialog() {
        AlertDialog.Builder(requireContext()).setMessage(getString(R.string.login_out_message))
            .setPositiveButton(getString(R.string.submit)) { _, _ ->
                if (mViewModel.isLogin()) {
                    mViewModel.logOut(MainFragment@ this)
                }
            }
            .setNegativeButton(getString(R.string.cancel), null)
            .show()
    }

    /**
     * 侧边栏列表点击事件
     */
    private fun onMenuItemClick(view: View, directions: NavDirections) {
        if (mViewModel.isLogin()) {
            Navigation.findNavController(view).navigate(directions)
        } else {
            Navigation.findNavController(view).navigate(StartNavigationDirections.mainToLogin())
        }
    }

    /**
     *  侧边栏头部登录点击事件
     */
    fun onHeaderClick(view: View) {
        if (!mViewModel.isLogin()) {
            Navigation.findNavController(view).navigate(StartNavigationDirections.mainToLogin())
        } else {
            Toast.makeText(requireContext(), R.string.already_login, Toast.LENGTH_SHORT).show()
        }
    }
}